package com.xb.cloud.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

public class BeanUtils extends org.springframework.beans.BeanUtils {
	

	private static final Logger LOGGER = LoggerFactory.getLogger(BeanUtils.class);

	public static <T> T convertMapToBean(Class<T> clazz, Map<?, ?> map) {
		T instantiateClass = instantiateClass(clazz);
		BeanWrapper beanWrapper = new BeanWrapperImpl(instantiateClass);
		beanWrapper.setPropertyValues(map);
		return instantiateClass;
	}
	
	/**
	 * <p>
	 * targetClazz必须有无参数的构造方法 .基础pojo=>转换目标bo;
	 * </p>
	 * @param targetClazz
	 * @param source
	 * @return
	 */
	public static <T> T newAndCopyProperties(Class<T> targetClazz, Object source){
		T target=null;
		try {
			target = targetClazz.newInstance();
		} catch ( Exception e) {
			String msg = "创建实例对象失败,类名:"+targetClazz.getName();
			LOGGER.error(msg);
			e.printStackTrace(); 
			throw new RuntimeException(msg);
		}
		copyProperties(source, target);
		return target;
	}
	
	/**
	 * <p>
	 * targetClazz必须有无参数的构造方法. 基础pojo列表=>转换目标bo列表;
	 * </p>
	 * 
	 * @param targetClazz
	 * @param source
	 * @return
	 */
	public static <T> List<T> newListAndCopyProperties(Class<T> targetClazz, List<?> sourceList) {
		List<T> targetList = new ArrayList<T>();
		if (sourceList == null || sourceList.size() == 0) {
			return null;
		}
		for (Object source : sourceList) {
			T target = newAndCopyProperties(targetClazz, source);
			targetList.add(target);
		}
		return targetList;
	}
}
